﻿using Google.Protobuf;
using System;
using System.Collections.Generic;
using System.Text;

namespace Cemit.PolyProto
{
    public static class MessageEncoding
    {
        public static byte[] Encode(IMessage message)
        {
            return message.ToByteArray();
        }

        public static IMessage Decode(string protoName, byte[] bytes)
        {
            if (Type.GetType(protoName) == null)
            {
                return null;
            }

            return GetMessage().Descriptor.Parser.ParseFrom(bytes);

            IMessage GetMessage()
                => (IMessage)Type.GetType(protoName).Assembly.CreateInstance(protoName);
        }

        public static byte[] EncodeName(IMessage message)
        {
            byte[] nameBytes = Encoding.UTF8.GetBytes(message.Descriptor.FullName);
            short length = (short)nameBytes.Length;
            byte[] ret = new byte[2 + length];
            //使用小端模式储存，即低位在前
            ret[0] = (byte)(length % 256);
            ret[1] = (byte)(length / 256);
            Array.Copy(nameBytes, 0, ret, 2, length);
            return ret;
        }

        public static string DecodeName(byte[] bytes, int offset, out int count)
        {
            count = 0;
            if (offset + 2 > bytes.Length)
            {
                return "";
            }
            short length = (short)((bytes[offset + 1] << 8) | bytes[offset]);
            if (offset + 2 + length > bytes.Length)
            {
                return "";
            }
            count = 2 + length;
            return Encoding.UTF8.GetString(bytes, offset + 2, length);
        }
    }
}
